{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "foldname='fold3_noFIR'\n",
    "# load_path='/media/taufiq/Data/heart_sound/models/fold0_noFIR 2018-01-16 17:25:30.579232/weights.0195-0.7422.hdf5'\n",
    "# load_path ='/media/taufiq/Data/heart_sound/models/fold0_noFIR 2018-01-29 16:18:29.392364/weights.0198-0.7488.hdf5'\n",
    "# load_path='/media/taufiq/Data/heart_sound/models/fold1_noFIR 2018-01-16 19:58:54.149714/weights.0182-0.8773.hdf5'\n",
    "# load_path= '/media/taufiq/Data/heart_sound/models/fold2_noFIR 2018-01-16 13:40:22.284989/weights.0137-0.8803.hdf5'\n",
    "load_path='/media/taufiq/Data/heart_sound/models/fold3_noFIR 2018-01-16 19:59:03.934614/weights.0126-0.8582.hdf5'\n",
    "# linear phase\n",
    "# load_path='/media/taufiq/Data/heart_sound/models/fold1_noFIR 2018-01-24 16:28:06.346153/weights.0191-0.8958.hdf5'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Using TensorFlow backend.\n"
     ]
    }
   ],
   "source": [
    "from heartnet_v1 import heartnet, reshape_folds\n",
    "\n",
    "random_seed=1\n",
    "batch_size=64\n",
    "fold_dir='/media/taufiq/Data/heart_sound/feature/potes_1DCNN/balancedCV/folds/'\n",
    "log_dir= '/media/taufiq/Data/heart_sound/Heart_Sound/codes/logs/'\n",
    "bn_momentum = 0.99\n",
    "eps= 1.1e-5\n",
    "bias=False\n",
    "l2_reg=0.\n",
    "l2_reg_dense=0.\n",
    "kernel_size=5\n",
    "maxnorm=10000.\n",
    "dropout_rate=0.5\n",
    "dropout_rate_dense=0.\n",
    "padding='valid'\n",
    "activation_function='relu'\n",
    "subsam=2\n",
    "lr=0.0012843784 \n",
    "lr_decay=0.0001132885\n",
    "FIR_train=True\n",
    "num_filt=(8,4)\n",
    "num_dense=20\n",
    "\n",
    "model = heartnet(activation_function, bn_momentum, bias, dropout_rate, dropout_rate_dense,\n",
    "             eps, kernel_size, l2_reg, l2_reg_dense, load_path, lr, lr_decay, maxnorm,\n",
    "             padding, random_seed, subsam, num_filt, num_dense, FIR_train)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(77631, 2500, 1)\n",
      "(77631, 1)\n",
      "(10224, 2500, 1)\n",
      "(10224, 1)\n",
      "loading complete\n"
     ]
    }
   ],
   "source": [
    "import tables\n",
    "feat = tables.open_file(fold_dir + foldname + '.mat')\n",
    "x_train = feat.root.trainX[:]\n",
    "y_train = feat.root.trainY[0, :]\n",
    "x_val = feat.root.valX[:]\n",
    "y_val = feat.root.valY[0, :]\n",
    "train_parts = feat.root.train_parts[:]\n",
    "val_parts = feat.root.val_parts[0, :]\n",
    "\n",
    "for i in range(0, y_train.shape[0]):\n",
    "    if y_train[i] == -1:\n",
    "        y_train[i] = 0  ## Label 0 for normal 1 for abnormal\n",
    "for i in range(0, y_val.shape[0]):\n",
    "    if y_val[i] == -1:\n",
    "        y_val[i] = 0\n",
    "x_train, y_train, x_val, y_val = reshape_folds(x_train, x_val, y_train, y_val)\n",
    "print \"loading complete\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 0.90654194]\n",
      " [ 0.92800832]\n",
      " [ 0.92194003]\n",
      " ..., \n",
      " [ 0.22791362]\n",
      " [ 0.5423705 ]\n",
      " [ 0.38783512]]\n"
     ]
    }
   ],
   "source": [
    "y_pred=model.predict(x_val)\n",
    "print y_pred"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "(342,)\n"
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "true = []\n",
    "pred=[]\n",
    "qual=[]\n",
    "start_idx = 0\n",
    "print val_parts.shape\n",
    "for s in val_parts:\t\n",
    "\t\n",
    "\tif s==0:\t\t## for e1,32,39,44 in validation0 there was no cardiac cycle\n",
    "            pred.append(0)\n",
    "            true.append(0)\n",
    "            qual.append(0)\n",
    "            continue \n",
    "\t#~ print \"part {} start {} stop {}\".format(s,start_idx,start_idx+int(s)-1)\n",
    "\t\t\t\t\t\n",
    "\ttemp_ = np.mean(y_val[start_idx:start_idx+int(s)-1])\n",
    "\ttemp = np.mean(y_pred[start_idx:start_idx+int(s)-1,:])\n",
    "# \tqual_ = np.mean(y_qual[start_idx:start_idx+int(s)-1,:])\n",
    "\t\n",
    "\tpred.append(temp)\n",
    "\ttrue.append(temp_)\n",
    "# \tqual.append(qual_)\n",
    "\t\n",
    "\tstart_idx = start_idx + int(s)\t\t\n",
    "\n",
    "true=np.array(true)\n",
    "pred=np.array(pred)\n",
    "# qual=np.array(qual)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "list_path='/media/taufiq/Data/heart_sound/feature/potes_1DCNN/balancedCV/'+'validation'+foldname[4]+'.txt'\n",
    "import pandas as pd\n",
    "val_list=pd.read_csv(list_path,header=None)\n",
    "val_list=val_list.values\n",
    "flat_list = [item[0] for sublist in val_list for item in sublist]\n",
    "flat_list=sorted(flat_list)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>0</th>\n",
       "      <th>Index</th>\n",
       "      <th>True</th>\n",
       "      <th>Pred</th>\n",
       "      <th>Error</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>a</td>\n",
       "      <td>0</td>\n",
       "      <td>1.0</td>\n",
       "      <td>0.931167</td>\n",
       "      <td>0.068833</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>a</td>\n",
       "      <td>1</td>\n",
       "      <td>1.0</td>\n",
       "      <td>0.513489</td>\n",
       "      <td>0.486511</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>a</td>\n",
       "      <td>2</td>\n",
       "      <td>1.0</td>\n",
       "      <td>0.750857</td>\n",
       "      <td>0.249143</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>a</td>\n",
       "      <td>3</td>\n",
       "      <td>1.0</td>\n",
       "      <td>0.915872</td>\n",
       "      <td>0.084128</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>a</td>\n",
       "      <td>4</td>\n",
       "      <td>1.0</td>\n",
       "      <td>0.755655</td>\n",
       "      <td>0.244345</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   0  Index  True      Pred     Error\n",
       "0  a      0   1.0  0.931167  0.068833\n",
       "1  a      1   1.0  0.513489  0.486511\n",
       "2  a      2   1.0  0.750857  0.249143\n",
       "3  a      3   1.0  0.915872  0.084128\n",
       "4  a      4   1.0  0.755655  0.244345"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "flat_list=pd.DataFrame(flat_list)\n",
    "flat_list['Index']=pd.DataFrame(range(0,val_parts.shape[0]))\n",
    "flat_list['True']=pd.DataFrame(true)\n",
    "flat_list['Pred']=pd.DataFrame(pred)\n",
    "flat_list['Error']=pd.DataFrame(abs(true-pred))\n",
    "flat_list.head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0.886363636364\n",
      "0.7\n",
      "0.833333333333\n",
      "0.8\n",
      "1.0\n",
      "0.571428571429\n"
     ]
    }
   ],
   "source": [
    "for dataset in ['a','b','c','d','e','f']: \n",
    "    print sum(flat_list['Error'][flat_list[0]==dataset].values<.5)/np.float32(flat_list[flat_list[0]==dataset].shape[0])\n",
    "# print sum(flat_list['Error']<.5)/342."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 2",
   "language": "python",
   "name": "python2"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
